package net;

import java.io.IOException;
import java.net.*;
import java.util.Date;
import java.util.Scanner;

/**
 * Creat by TanLei
 * Description:
 * User:86183
 * Date:2022-06-16
 * Time:13:51
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpEchoClient(String ip,int port) throws SocketException{
        serverIP = ip;
        serverPort = port;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("->");
            String request = scanner.next();
            if(request.equals("exit")){
                System.out.println("good bye!");
                break;
            }
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);

            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.printf("req: %s; resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();

    }
}
